<template>
  <div>
    <!-- 图片，把它当作按钮 -->
    <div class="btn_img" @click="openDialog()">
      <img :src="coverImageUrl" />
    </div>

    <!-- 对话框 -->
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="images">
          <el-radio-group
            v-model="isCollected"
            size="mini"
            @change="hSwitchCollect"
            style="padding-bottom: 15px"
          >
            <el-radio-button label="全部"></el-radio-button>
            <el-radio-button label="收藏"></el-radio-button>
          </el-radio-group>
          <el-row :gutter="10">
            <el-col
              :span="4"
              v-for="image in images"
              :key="image.id"
              class="img_item"
              :class="{selected: selectedImageUrl == image.url}"
            >
              <el-image
                style="height: 110px; width: 110px"
                :src="image.url"
                fit="cover"
                @click="hSelectImage(image)"
              ></el-image>
            </el-col>
          </el-row>
          <!-- 列表分页 -->
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="per_page"
            @current-change="hPageChange"
            :total="total_count"
            :disabled="isLoading"
          >
          </el-pagination>
          <!-- /列表分页 -->
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="uploads">
          <el-upload
            class="avatar-uploader"
            action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image
              v-if="uploadImageUrl"
              :src="uploadImageUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="hConfirm" size="small"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '../../assets/default.png'
export default {
  name: 'cover',
  props: ['value'],
  data () {
    return {
      selectedImageUrl: '', // 记录当前用户选中的是哪一张图片（url）
      // 图片按钮默认显示的图片以及用户选中的图片地址
      coverImageUrl: defaultImg,
      dialogVisible: false, // 是否弹出对话框
      activeName: 'images',
      isCollected: '全部', // 素材库中的全部或收藏状态
      images: [], // 后端返回的素材库的图片列表
      page: 1,
      total_count: 0,
      per_page: 12,
      isLoading: false,
      uploadImageUrl: '', // 用户上传的图片的地址
      headers: { // 请求头
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      }
    };
  },
  methods: {
    buildParams () {
      const params = {
        page: this.page,
        per_page: this.per_page,
        collect: this.isCollected === '收藏'
      };
      return params;
    },
    async getImages () {
      const params = this.buildParams();
      try {
        const res = await this.$axios({
          url: '/mp/v1_0/user/images',
          method: 'GET',
          params
        });
        this.images = res.data.data.results;
        this.total_count = res.data.data.total_count;
      } catch (err) {
        console.log(err);
      }
    },
    // 点击分页器回调
    hPageChange (curpage) {
      this.page = curpage;
      // 重新请求数据
      this.getImages();
    },
    // 切换全部、收藏的回调
    hSwitchCollect () {
      // 把页码重置为1
      this.page = 1;
      this.getImages();
    },
    // 打开弹出层执行的回调
    openDialog () {
      this.dialogVisible = true;
      this.getImages();
    },
    // 选中素材库图片执行的回调
    hSelectImage (image) {
      this.selectedImageUrl = image.url
      console.log(this.selectedImageUrl);
    },
    // 上传成功的回调函数
    handleAvatarSuccess (res, file) {
      console.log(res);
      console.log(file);
      this.uploadImageUrl = res.data.url;

      // 2. 重新获取
      this.getImages();
    },
    // 上传图片格式及文件大小限制
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    hConfirm () {
      if (this.activeName === 'images' && this.selectedImageUrl === '') {
        this.$message.error('请选择图片');
        return
      }
      if (this.activeName === 'uploads' && this.uploadImageUrl === '') {
        this.$message.error('请上传图片');
        return
      }
      this.coverImageUrl = this.activeName === 'images' ? this.selectedImageUrl : this.uploadImageUrl
      // 抛出input事件，以及图片url
      this.$emit('input', this.coverImageUrl)
      // 关闭对话框
      this.dialogVisible = false
    }
  },
  // 侦听器
  watch: {
    value: {
      handler: function (newVlaue, oldValue) {
        console.log(newVlaue, oldValue);
        if (newVlaue) {
          this.coverImageUrl = newVlaue
        } else {
          this.coverImageUrl = defaultImg
        }
      },
      immediate: true
    }
  }
};
</script>

<style scoped lang='less'>
// 图片按钮
.btn_img {
  cursor: pointer;
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
.selected::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3) url(../../assets/selected.png) no-repeat center /
    50px 50px;
}
.img_item {
  position: relative;
  box-sizing: border-box;
  /deep/ img {
      cursor: pointer
    }
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
